package king.dominic.jlibrary.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


/**
 * Created by Administrator on 2017/11/1.
 * DatabaseFactory
 */

public class DatabaseFactory {
    private DatabaseFactory(){}

    public static  SQLiteOpenHelper newDatabaseOpenHelper(Context context, String name, TableFactory... tableFactories) {
        int version = 1;
        for (TableFactory tf : tableFactories) {
            version = Math.max(tf.mLastVersion, version);
        }
        return new DatabaseOpenHelper(context, name, version, tableFactories);
    }

    private static class DatabaseOpenHelper extends SQLiteOpenHelper {

        private final TableFactory[] tableFactories;

        private DatabaseOpenHelper(Context context, String name, int version, TableFactory... tableFactories) {
            super(context, name, null, version);
            this.tableFactories = tableFactories;
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            for (TableFactory tf : tableFactories) {
                tf.create(db);
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

            for (TableFactory tf : tableFactories) {
                tf.upgrade(db, oldVersion, newVersion);
            }
        }
    }
}
